<script setup>
import { ref, onMounted, computed, watch } from "vue";
import { useRouter } from "vue-router";
import { useUserStore } from "@/stores/user.js";
import { useExamStore } from "@/stores/exam.js";
import { usePlanStores } from "@/stores/training-plan.js";
import { useLogService } from "@/stores/logService.js";
import { useCourseStore } from "@/stores/course.js"; // 新增
import * as echarts from "echarts";

const router = useRouter();
const userStore = useUserStore();
const examStore = useExamStore();
const planStore = usePlanStores();
const logService = useLogService();
const courseStore = useCourseStore(); // 新增
// 统计数据
const stats = ref({
  totalUsers: 0, // 初始值为 0
  activeUsers: 842,
  trainers: 0, // 初始值为 0
  pendingUsers: 18,
  activeCourses: 64,
  totalExams: 42,
  completedExams: 28,
  trainingPlans: 15,
  activeTrainingPlans: 12,
});
const totalCourses = computed(() => courseStore.courses.length);
// 最近活动日志
const recentLogs = ref([]);
const loading = ref(false);
const dialogVisible = ref(false);
const selectedLog = ref(null);
// 用户分布数据
// 用户分布数据
const userDistribution = ref([]); // 【修改】初始值改为空数组

// 【新增】创建计算属性，用于动态计算课程分类及其数量
const courseCategoryDistribution = computed(() => {
  const categoryMap = new Map();
  // 遍历 store 中的课程列表
  for (const item of courseStore.courses) {
    // 如果课程有分类名，则使用它，否则归为“未分类”
    const categoryName = item.course.categoryName || '未分类';
    // 在 Map 中累加每个分类的数量
    categoryMap.set(categoryName, (categoryMap.get(categoryName) || 0) + 1);
  }
  // 将 Map 转换为 ECharts 需要的 [{ name: '分类名', value: 数量 }] 格式
  return Array.from(categoryMap, ([name, value]) => ({ name, value }));
});

// 课程分类数据
// const courseCategories = ref([
//   { value: 32, name: "基础护理" },
//   { value: 24, name: "专科护理" },
//   { value: 18, name: "急救技能" },
//   { value: 12, name: "护理管理" },
// ]);

// 【新增】获取用户数据并更新统计卡片
// 【修改】获取用户数据并更新统计卡片和图表
const fetchUserStats = () => {
  userStore.fetchAllUsers(
    (userList) => {
      // 成功获取到用户列表的回调
      if (Array.isArray(userList)) {
        // --- 更新统计卡片 (这部分逻辑保留) ---
        stats.value.totalUsers = userList.length;
        stats.value.trainers = userList.filter(user => user.roleId === 2).length;

        // --- 【新增】计算用户分布 ---
        const admins = userList.filter(user => user.roleId === 1).length;
        const teachers = userList.filter(user => user.roleId === 2).length;
        const students = userList.filter(user => user.roleId === 3).length;

        // 更新图表数据源
        userDistribution.value = [
          { value: students, name: "学员" },
          { value: teachers, name: "培训导师" },
          { value: admins, name: "管理员" },
        ];

        // --- 【新增】用新数据重新渲染图表 ---
        // 确保图表在拿到新数据后立即更新
        initUserDistributionChart();
      }
    },
    (error) => {
      // 失败的回调
      console.error("获取用户统计数据失败:", error);
    }
  );
};

// 考核通过率数据
// const examPassRates = ref([
//   { month: "1月", passRate: 85 },
//   { month: "2月", passRate: 82 },
//   { month: "3月", passRate: 88 },
//   { month: "4月", passRate: 90 },
//   { month: "5月", passRate: 86 },
//   { month: "6月", passRate: 92 },
// ]);
// 考核通过率数据
const examPassRates = ref([]); // 【修改】初始值改为空数组

// 系统访问量数据
const systemVisits = ref([
  { date: "周一", visits: 120 },
  { date: "周二", visits: 132 },
  { date: "周三", visits: 101 },
  { date: "周四", visits: 134 },
  { date: "周五", visits: 90 },
  { date: "周六", visits: 70 },
  { date: "周日", visits: 60 },
]);

// 获取最近的操作日志
const fetchRecentLogs = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: 1,
      pageSize: 10,
    };
    const response = await logService.queryOperationLogs(params);
    recentLogs.value = response.records || [];
  } catch (error) {
    console.error("获取日志列表失败:", error);
  } finally {
    loading.value = false;
  }
};

// 【新增】获取考核和答卷数据，并更新统计
const fetchExamStats = () => {
  // 1. 获取考核总数来更新卡片
  examStore.fetchExams(
    {}, // 使用空参数，让后端返回默认分页数据
    (data, total) => {
      // 这个回调的第二个参数 'total' 就是我们需要的考核总数
      stats.value.totalExams = total;
    }
  );

  // 2. 获取所有答卷来计算通过率
  examStore.fetchAllSubmissions((submissions) => {
    // 确保有答卷数据
    if (!Array.isArray(submissions) || submissions.length === 0) {
      initExamPassRateChart(); // 如果没有数据，也调用一次来显示空图表
      return;
    }

    // A. 筛选出所有“已完成”的答卷
    const completed = submissions.filter(
      (sub) => sub.examSubmission?.gradingStatus === 'completed'
    );

    // B. 按提交日期进行分组
    const submissionsByDay = completed.reduce((acc, sub) => {
      // 获取提交日期，格式化为 'YYYY-MM-DD'
      const day = new Date(sub.examSubmission.submitTime).toISOString().split('T')[0];
      // 如果这个日期还没在累加器里，就创建一个空数组
      if (!acc[day]) {
        acc[day] = [];
      }
      // 将当前答卷推进对应的日期数组
      acc[day].push(sub);
      return acc;
    }, {});

    // C. 计算每天的通过率
    const dailyPassRates = Object.entries(submissionsByDay).map(([day, dailySubs]) => {
      const totalCount = dailySubs.length;
      if (totalCount === 0) {
        return { date: day, passRate: 0 };
      }
      // 计算及格的人数 (总分 >= 60)
      const passedCount = dailySubs.filter(
        (sub) => sub.examSubmission.totalScore >= 60
      ).length;
      // 计算通过率
      const passRate = (passedCount / totalCount) * 100;
      return {
        date: day,
        passRate: parseFloat(passRate.toFixed(1)) // 保留一位小数
      };
    });

    // D. 按日期排序并更新图表数据源
    examPassRates.value = dailyPassRates.sort((a, b) => new Date(a.date) - new Date(b.date));

    // E. 用新数据重新渲染图表
    initExamPassRateChart();
  });
};

// 初始化用户分布图表
const initUserDistributionChart = () => {
  const chartDom = document.getElementById("user-distribution-chart");
  if (chartDom) {
    const chart = echarts.init(chartDom);
    const option = {
      tooltip: {
        trigger: "item",
        formatter: "{a} <br/>{b}: {c} ({d}%)",
      },
      legend: {
        orient: "vertical",
        left: 10,
        data: userDistribution.value.map((item) => item.name),
      },
      series: [
        {
          name: "用户分布",
          type: "pie",
          radius: ["50%", "70%"],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: "#fff",
            borderWidth: 2,
          },
          label: {
            show: false,
            position: "center",
          },
          emphasis: {
            label: {
              show: true,
              fontSize: "18",
              fontWeight: "bold",
            },
          },
          labelLine: {
            show: false,
          },
          data: userDistribution.value,
        },
      ],
    };
    chart.setOption(option);
    window.addEventListener("resize", () => {
      chart.resize();
    });
  }
};

// ...紧跟在 fetchRecentLogs 函数后

// 【新增】获取系统登录日志并处理为周访问量数据
const fetchSystemVisits = async () => {
  try {
    // 1. 调用接口获取最近的登录日志，可以设置一个较大的pageSize以覆盖近期数据
    const logData = await logService.queryOperationLogs({
      pageSize: 1000, // 获取足够多的近期日志
      operationType: '登录' // 直接通过接口筛选登录操作，更高效
    });

    if (logData && Array.isArray(logData.records)) {
      // 2. 初始化一个按周一到周日排列的数组来存放访问量
      const visitsByWeekday = [0, 0, 0, 0, 0, 0, 0]; // 索引 0=周一, 6=周日

      // 3. 筛选出最近7天的日志并分组
      const today = new Date();
      const oneWeekAgo = new Date();
      oneWeekAgo.setDate(today.getDate() - 7);

      for (const log of logData.records) {
        const logDate = new Date(log.operationTime);

        // 只统计最近一周内的日志
        if (logDate >= oneWeekAgo) {
          let dayIndex = logDate.getDay(); // (0=周日, 1=周一, ..., 6=周六)

          // 将 getDay() 的返回值映射到我们的数组索引 (0=周一, ..., 6=周日)
          dayIndex = dayIndex === 0 ? 6 : dayIndex - 1;

          visitsByWeekday[dayIndex]++;
        }
      }

      // 4. 更新 ECharts 需要的数据源
      const dayLabels = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];
      systemVisits.value = dayLabels.map((label, index) => ({
        date: label,
        visits: visitsByWeekday[index]
      }));

      // 5. 用新数据重新渲染图表
      initSystemVisitsChart();
    }
  } catch (error) {
    console.error("获取系统访问数据失败:", error);
    // 即使失败，也渲染一个空图表
    initSystemVisitsChart();
  }
};


// 初始化课程分类图表
// const initCourseCategoriesChart = () => {
//   const chartDom = document.getElementById("course-categories-chart");
//   if (chartDom) {
//     const chart = echarts.init(chartDom);
//     const option = {
//       tooltip: {
//         trigger: "item",
//         formatter: "{a} <br/>{b}: {c} ({d}%)",
//       },
//       legend: {
//         orient: "vertical",
//         left: 10,
//         data: courseCategories.value.map((item) => item.name),
//       },
//       series: [
//         {
//           name: "课程分类",
//           type: "pie",
//           radius: "50%",
//           data: courseCategories.value, // 修改这里
//           emphasis: {
//             itemStyle: {
//               shadowBlur: 10,
//               shadowOffsetX: 0,
//               shadowColor: "rgba(0, 0, 0, 0.5)",
//             },
//           },
//         },
//       ],
//     };
//     chart.setOption(option);
//     window.addEventListener("resize", () => {
//       chart.resize();
//     });
//   }
// };
// 【修改】初始化课程分类图表，使其使用动态数据
const initCourseCategoriesChart = () => {
  const chartDom = document.getElementById("course-categories-chart");
  if (chartDom) {
    const chart = echarts.init(chartDom);
    const option = {
      tooltip: {
        trigger: "item",
        formatter: "{a} <br/>{b}: {c} ({d}%)",
      },
      legend: {
        orient: "vertical",
        left: 10,
        // 使用新的计算属性来生成图例
        data: courseCategoryDistribution.value.map((item) => item.name),
      },
      series: [
        {
          name: "课程分类",
          type: "pie",
          radius: "50%",
          // 使用新的计算属性来填充数据
          data: courseCategoryDistribution.value,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
        },
      ],
      // 如果没有数据，显示一个提示
      graphic: {
        type: 'text',
        left: 'center',
        top: 'center',
        style: {
          fill: '#999',
          text: '暂无课程分类数据',
          font: '14px Microsoft YaHei'
        },
        invisible: courseCategoryDistribution.value.length > 0
      }
    };
    chart.setOption(option);
    window.addEventListener("resize", () => {
      chart.resize();
    });
  }
};

// 初始化考核通过率图表
// const initExamPassRateChart = () => {
//   const chartDom = document.getElementById("exam-pass-rate-chart");
//   if (chartDom) {
//     const chart = echarts.init(chartDom);
//     const option = {
//       tooltip: {
//         trigger: "axis",
//         axisPointer: {
//           type: "shadow",
//         },
//       },
//       grid: {
//         left: "3%",
//         right: "4%",
//         bottom: "3%",
//         containLabel: true,
//       },
//       xAxis: [
//         {
//           type: "category",
//           data: examPassRates.value.map((item) => item.month),
//           axisTick: {
//             alignWithLabel: true,
//           },
//         },
//       ],
//       yAxis: [
//         {
//           type: "value",
//           name: "通过率(%)",
//           min: 0,
//           max: 100,
//         },
//       ],
//       series: [
//         {
//           name: "通过率",
//           type: "bar",
//           barWidth: "60%",
//           data: examPassRates.value.map((item) => item.passRate),
//           itemStyle: {
//             color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
//               { offset: 0, color: "#83bff6" },
//               { offset: 0.5, color: "#188df0" },
//               { offset: 1, color: "#188df0" },
//             ]),
//           },
//         },
//       ],
//     };
//     chart.setOption(option);
//     window.addEventListener("resize", () => {
//       chart.resize();
//     });
//   }
// };
// 【修改】初始化考核通过率图表
const initExamPassRateChart = () => {
  const chartDom = document.getElementById("exam-pass-rate-chart");
  if (chartDom) {
    const chart = echarts.init(chartDom);
    const option = {
      tooltip: {
        trigger: "axis",
        axisPointer: { type: "shadow" },
        // 增加 formatter 使提示更友好
        formatter: '{b}<br/>通过率: {c}%'
      },
      grid: {
        left: "3%",
        right: "4%",
        bottom: "3%",
        containLabel: true,
      },
      xAxis: [
        {
          type: "category",
          // X轴数据从新的 examPassRates 中获取 date 字段
          data: examPassRates.value.map((item) => item.date),
          axisTick: { alignWithLabel: true },
        },
      ],
      yAxis: [
        {
          type: "value",
          name: "通过率(%)",
          min: 0,
          max: 100,
        },
      ],
      series: [
        {
          name: "通过率",
          type: "bar",
          barWidth: "60%",
          // Y轴数据从新的 examPassRates 中获取 passRate 字段
          data: examPassRates.value.map((item) => item.passRate),
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: "#83bff6" },
              { offset: 0.5, color: "#188df0" },
              { offset: 1, color: "#188df0" },
            ]),
          },
        },
      ],
      // 如果没有数据，显示一个提示
      graphic: {
        type: 'text',
        left: 'center',
        top: 'center',
        style: {
          fill: '#999',
          text: '暂无考核通过率数据',
          font: '14px Microsoft YaHei'
        },
        invisible: examPassRates.value.length > 0
      }
    };
    chart.setOption(option);
    window.addEventListener("resize", () => {
      chart.resize();
    });
  }
};

// 初始化系统访问量图表
const initSystemVisitsChart = () => {
  const chartDom = document.getElementById("system-visits-chart");
  if (chartDom) {
    const chart = echarts.init(chartDom);
    const option = {
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "cross",
          label: {
            backgroundColor: "#6a7985",
          },
        },
      },
      grid: {
        left: "3%",
        right: "4%",
        bottom: "3%",
        containLabel: true,
      },
      xAxis: [
        {
          type: "category",
          boundaryGap: false,
          data: systemVisits.value.map((item) => item.date),
        },
      ],
      yAxis: [
        {
          type: "value",
        },
      ],
      series: [
        {
          name: "访问量",
          type: "line",
          stack: "总量",
          areaStyle: {},
          emphasis: {
            focus: "series",
          },
          data: systemVisits.value.map((item) => item.visits),
        },
      ],
    };
    chart.setOption(option);
    window.addEventListener("resize", () => {
      chart.resize();
    });
  }
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return "-";
  return new Date(dateTime).toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
};

// 获取操作类型标签样式
const getOperationTypeTagType = (type) => {
  switch (type) {
    case "登录":
      return "success";
    case "创建":
      return "primary";
    case "更新":
      return "warning";
    case "删除":
      return "danger";
    default:
      return "info";
  }
};
watch(courseCategoryDistribution, (newValue) => {
  // 只有当 newValue (也就是计算后的图表数据) 不为空时才绘制
  if (newValue && newValue.length > 0) {
    initCourseCategoriesChart();
  }
});
const fetchPlanStats = async () => {
  try {
    // 调用更新后的 store action，并等待结果
    const allPlans = await planStore.getAllPlans();
    // 确保返回的是一个数组
    if (Array.isArray(allPlans)) {
      // 使用数组的长度来更新统计卡片上的“培训计划”数量
      stats.value.trainingPlans = allPlans.length;
    }
  } catch (error) {
    console.error("获取培训计划统计数据失败:", error);
    stats.value.trainingPlans = 0; // 如果获取失败，则显示为0
  }
};
const handleViewDetails = (log) => {
  selectedLog.value = log;
  dialogVisible.value = true;
};

// 页面加载时初始化数据和图表
onMounted(() => {
  fetchUserStats();
  fetchRecentLogs();
  fetchExamStats();
  fetchPlanStats();
  fetchSystemVisits();
  courseStore.getCourses();
  // 延迟初始化图表，确保DOM已经渲染
  setTimeout(() => {
    initUserDistributionChart();
    // initCourseCategoriesChart();
    initExamPassRateChart();
    //initSystemVisitsChart();
  }, 100);
});

// 导航方法
const navigateTo = (path) => {
  router.push(path);
};
</script>

<template>
  <div class="admin-dashboard-container">
    <!-- 欢迎信息 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="24">
        <el-card shadow="never" class="welcome-card">
          <div class="d-flex align-items-center">
            <div class="welcome-icon">
              <i class="bi bi-person-circle"></i>
            </div>
            <div class="welcome-text">
              <h2>欢迎回来，管理员</h2>
              <p>
                今天是
                {{
                  new Date().toLocaleDateString("zh-CN", {
                    year: "numeric",
                    month: "long",
                    day: "numeric",
                    weekday: "long",
                  })
                }}，祝您工作愉快！
              </p>
            </div>
            <div class="ms-auto">
              <el-button type="primary" @click="navigateTo('/admin/log')">
                <i class="bi bi-activity me-1"></i> 查看系统日志
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24" class="mb-4">
        <el-card class="box-card stats-card" shadow="hover">
          <div class="d-flex align-items-center">
            <div class="flex-grow-1 me-3">
              <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                总用户数
              </div>
              <div class="h5 mb-0 font-weight-bold text-gray-800">
                {{ stats.totalUsers }}
              </div>
            </div>
            <div class="flex-shrink-0">
              <i class="bi bi-people-fill fa-2x text-gray-300"></i>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24" class="mb-4">
        <el-card class="box-card stats-card" shadow="hover">
          <div class="d-flex align-items-center">
            <div class="flex-grow-1 me-3">
              <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                总课程数
              </div>
              <div class="h5 mb-0 font-weight-bold text-gray-800">
                {{ totalCourses }}
              </div>
            </div>
            <div class="flex-shrink-0">
              <i class="bi bi-book-fill fa-2x text-gray-300"></i>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24" class="mb-4">
        <el-card class="box-card stats-card" shadow="hover">
          <div class="d-flex align-items-center">
            <div class="flex-grow-1 me-3">
              <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                考核数量
              </div>
              <div class="h5 mb-0 font-weight-bold text-gray-800">
                {{ stats.totalExams }}
              </div>
            </div>
            <div class="flex-shrink-0">
              <i class="bi bi-clipboard2-check-fill fa-2x text-gray-300"></i>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24" class="mb-4">
        <el-card class="box-card stats-card" shadow="hover">
          <div class="d-flex align-items-center">
            <div class="flex-grow-1 me-3">
              <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                培训计划
              </div>
              <div class="h5 mb-0 font-weight-bold text-gray-800">
                {{ stats.trainingPlans }}
              </div>
            </div>
            <div class="flex-shrink-0">
              <i class="bi bi-calendar2-check-fill fa-2x text-gray-300"></i>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24" class="mb-4">
        <el-card class="box-card" shadow="never">
          <template #header>
            <div class="card-header d-flex justify-content-between align-items-center">
              <h5 class="mb-0">用户分布</h5>
            </div>
          </template>
          <div id="user-distribution-chart" style="height: 300px"></div>
        </el-card>
      </el-col>
      <el-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24" class="mb-4">
        <el-card class="box-card" shadow="never">
          <template #header>
            <div class="card-header d-flex justify-content-between align-items-center">
              <h5 class="mb-0">课程分类分布</h5>
            </div>
          </template>
          <div id="course-categories-chart" style="height: 300px"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mb-4">
      <el-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24" class="mb-4">
        <el-card class="box-card" shadow="never">
          <template #header>
            <div class="card-header d-flex justify-content-between align-items-center">
              <h5 class="mb-0">考核通过率趋势</h5>
            </div>
          </template>
          <div id="exam-pass-rate-chart" style="height: 300px"></div>
        </el-card>
      </el-col>
      <el-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24" class="mb-4">
        <el-card class="box-card" shadow="never">
          <template #header>
            <div class="card-header d-flex justify-content-between align-items-center">
              <h5 class="mb-0">系统访问量</h5>
            </div>
          </template>
          <div id="system-visits-chart" style="height: 300px"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 快捷功能区 -->
    <!-- <el-row :gutter="20" class="mb-4">
      <el-col :span="24">
        <el-card class="box-card" shadow="never">
          <template #header>
            <div class="card-header">
              <h5 class="mb-0">快捷功能</h5>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24" class="mb-3">
              <el-card
                class="shortcut-card"
                shadow="hover"
                @click="navigateTo('/admin/admin-user')"
              >
                <div class="text-center">
                  <i class="bi bi-people-fill shortcut-icon"></i>
                  <h5 class="mt-2">用户管理</h5>
                  <p class="text-muted">管理系统用户和权限</p>
                </div>
              </el-card>
            </el-col>
            <el-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24" class="mb-3">
              <el-card
                class="shortcut-card"
                shadow="hover"
                @click="navigateTo('/admin/admin-course')"
              >
                <div class="text-center">
                  <i class="bi bi-book-fill shortcut-icon"></i>
                  <h5 class="mt-2">课程管理</h5>
                  <p class="text-muted">管理培训课程资源</p>
                </div>
              </el-card>
            </el-col>
            <el-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24" class="mb-3">
              <el-card
                class="shortcut-card"
                shadow="hover"
                @click="navigateTo('/admin/admin-exam')"
              >
                <div class="text-center">
                  <i class="bi bi-clipboard2-check-fill shortcut-icon"></i>
                  <h5 class="mt-2">考核管理</h5>
                  <p class="text-muted">管理考核评估系统</p>
                </div>
              </el-card>
            </el-col>
            <el-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24" class="mb-3">
              <el-card
                class="shortcut-card"
                shadow="hover"
                @click="navigateTo('/admin/admin-plan')"
              >
                <div class="text-center">
                  <i class="bi bi-calendar2-check-fill shortcut-icon"></i>
                  <h5 class="mt-2">培训计划</h5>
                  <p class="text-muted">管理培训计划安排</p>
                </div>
              </el-card>
            </el-col>
            <el-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24" class="mb-3">
              <el-card
                class="shortcut-card"
                shadow="hover"
                @click="navigateTo('/admin/admin-community')"
              >
                <div class="text-center">
                  <i class="bi bi-chat-dots-fill shortcut-icon"></i>
                  <h5 class="mt-2">社区管理</h5>
                  <p class="text-muted">管理培训交流社区</p>
                </div>
              </el-card>
            </el-col>
            <el-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24" class="mb-3">
              <el-card
                class="shortcut-card"
                shadow="hover"
                @click="navigateTo('/admin/log')"
              >
                <div class="text-center">
                  <i class="bi bi-activity shortcut-icon"></i>
                  <h5 class="mt-2">日志审计</h5>
                  <p class="text-muted">查看系统操作日志</p>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row> -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="24">
        <el-card class="box-card" shadow="never">
          <template #header>
            <div class="card-header">
              <h5 class="mb-0">快捷功能</h5>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24" class="mb-3">
              <el-card class="shortcut-card" shadow="hover" @click="navigateTo('/admin/user')">
                <div class="text-center">
                  <i class="bi bi-people-fill shortcut-icon"></i>
                  <h5 class="mt-2">用户管理</h5>
                  <p class="text-muted">管理系统用户和权限</p>
                </div>
              </el-card>
            </el-col>
            <el-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24" class="mb-3">
              <el-card class="shortcut-card" shadow="hover" @click="navigateTo('/admin/admin-course')">
                <div class="text-center">
                  <i class="bi bi-book-fill shortcut-icon"></i>
                  <h5 class="mt-2">课程管理</h5>
                  <p class="text-muted">管理培训课程资源</p>
                </div>
              </el-card>
            </el-col>
            <el-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24" class="mb-3">
              <el-card class="shortcut-card" shadow="hover" @click="navigateTo('/admin/admin-assessment')">
                <div class="text-center">
                  <i class="bi bi-clipboard2-check-fill shortcut-icon"></i>
                  <h5 class="mt-2">考核管理</h5>
                  <p class="text-muted">管理考核评估系统</p>
                </div>
              </el-card>
            </el-col>
            <!-- <el-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24" class="mb-3">
              <el-card class="shortcut-card" shadow="hover" @click="navigateTo('/admin/admin-training-plan')">
                <div class="text-center">
                  <i class="bi bi-calendar2-check-fill shortcut-icon"></i>
                  <h5 class="mt-2">培训计划</h5>
                  <p class="text-muted">管理培训计划安排</p>
                </div>
              </el-card>
            </el-col> -->
            <el-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24" class="mb-3">
              <el-card class="shortcut-card" shadow="hover" @click="navigateTo('/community')">
                <div class="text-center">
                  <i class="bi bi-chat-dots-fill shortcut-icon"></i>
                  <h5 class="mt-2">社区广场</h5>
                  <p class="text-muted">管理培训交流社区</p>
                </div>
              </el-card>
            </el-col>
            <el-col :xl="4" :lg="6" :md="8" :sm="12" :xs="24" class="mb-3">
              <el-card class="shortcut-card" shadow="hover" @click="navigateTo('/admin/log')">
                <div class="text-center">
                  <i class="bi bi-activity shortcut-icon"></i>
                  <h5 class="mt-2">日志审计</h5>
                  <p class="text-muted">查看系统操作日志</p>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
    <!-- 最近操作日志 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="box-card" shadow="never">
          <template #header>
            <div class="card-header d-flex justify-content-between align-items-center">
              <h5 class="mb-0">最近操作日志</h5>
              <el-button size="small" @click="fetchRecentLogs" :loading="loading">
                <i class="bi bi-arrow-clockwise me-1"></i> 刷新
              </el-button>
            </div>
          </template>
          <el-table :data="recentLogs" v-loading="loading" stripe style="width: 100%">
            <el-table-column prop="id" label="ID" width="80"></el-table-column>
            <el-table-column prop="userId" label="用户ID" width="100"></el-table-column>
            <el-table-column prop="operationType" label="操作类型" width="120">
              <template #default="scope">
                <el-tag :type="getOperationTypeTagType(scope.row.operationType)" size="small">
                  {{ scope.row.operationType || "未知操作" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="operationTime" label="操作时间" width="180">
              <template #default="scope">
                {{ formatDateTime(scope.row.operationTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="ipAddress" label="IP地址" width="140"></el-table-column>
            <el-table-column prop="status" label="状态" width="80" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" size="small">
                  {{ scope.row.status === 1 ? "成功" : "失败" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="paramsSummary" label="参数摘要" min-width="200" show-overflow-tooltip></el-table-column>
            <!-- <el-table-column label="操作" width="100" fixed="right">
              <template #default="scope">
                <el-button type="text" size="small" @click="navigateTo('/admin/admin-log')">
                  详情
                </el-button>
              </template>
            </el-table-column> -->
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="scope">
                <el-button type="primary" link size="small" @click="handleViewDetails(scope.row)">
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="text-center mt-3" v-if="recentLogs.length > 0">
            <el-button type="primary" plain @click="navigateTo('/admin/log')">
              查看更多日志
            </el-button>
          </div>
          <el-empty v-if="recentLogs.length === 0 && !loading" description="暂无操作日志"></el-empty>
        </el-card>
      </el-col>
    </el-row>
  </div>
  <el-dialog v-model="dialogVisible" title="日志完整详情" width="60%">
    <el-form v-if="selectedLog" :model="selectedLog" label-position="right" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="ID:">
            <el-input :value="selectedLog.id" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="追踪ID (TraceId):">
            <el-input :value="selectedLog.traceId" readonly />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="父追踪ID:">
        <el-input :value="selectedLog.parentTraceId || '无'" readonly />
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户ID:">
            <el-input :value="selectedLog.userId" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="创建者ID:">
            <el-input :value="selectedLog.creatorId" readonly />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="权限ID:">
            <el-input :value="selectedLog.permissionId" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="资源ID:">
            <el-input :value="selectedLog.resourceId" readonly />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="操作时间:">
        <el-input :value="formatDateTime(selectedLog.operationTime)" readonly />
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="IP地址:">
            <el-input :value="selectedLog.ipAddress" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态:">
            <el-tag :type="selectedLog.status === 1 ? 'success' : 'danger'">
              {{ selectedLog.status === 1 ? "成功" : "失败" }}
            </el-tag>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="响应时间(ms):">
            <el-input :value="selectedLog.responseTime" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="资源类型:">
            <el-input :value="selectedLog.resourceType" readonly />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="参数摘要:">
        <el-input type="textarea" :rows="4" :value="selectedLog.paramsSummary" readonly />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
/* 引入Bootstrap图标 */
@import url("https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css");

/* 欢迎卡片样式 */
.welcome-card {
  background: linear-gradient(135deg, #4b6cb7 0%, #182848 100%);
  color: white;
}

.welcome-icon {
  font-size: 3rem;
  margin-right: 1.5rem;
}

.welcome-text h2 {
  margin: 0;
  font-size: 1.5rem;
}

.welcome-text p {
  margin: 0.5rem 0 0;
  opacity: 0.8;
}

/* 统计卡片样式 */
.stats-card {
  transition: transform 0.3s;
}

.stats-card:hover {
  transform: translateY(-5px);
}

.stats-card .el-card__body {
  padding: 16px;
}

/* 卡片头部样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid var(--el-border-color-light);
}

/* 快捷功能卡片样式 */
.shortcut-card {
  cursor: pointer;
  transition: all 0.3s;
  height: 100%;
}

.shortcut-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.shortcut-icon {
  font-size: 2.5rem;
  color: var(--el-color-primary);
}

/* 通用样式 */
.mb-4 {
  margin-bottom: 1.5rem;
}

.mb-3 {
  margin-bottom: 1rem;
}

.mt-2 {
  margin-top: 0.5rem;
}

.mt-3 {
  margin-top: 1rem;
}

.me-1 {
  margin-right: 0.25rem;
}

.me-3 {
  margin-right: 1rem;
}

.ms-auto {
  margin-left: auto;
}

.d-flex {
  display: flex;
}

.align-items-center {
  align-items: center;
}

.justify-content-between {
  justify-content: space-between;
}

.text-center {
  text-align: center;
}

.text-muted {
  color: #6c757d;
}

.text-xs {
  font-size: 0.75rem;
}

.text-uppercase {
  text-transform: uppercase;
}

.font-weight-bold {
  font-weight: bold;
}

.text-gray-800 {
  color: #5a5c69;
}

.text-primary {
  color: #4e73df;
}

.text-success {
  color: #1cc88a;
}

.text-info {
  color: #36b9cc;
}

.text-warning {
  color: #f6c23e;
}

.flex-grow-1 {
  flex-grow: 1;
}

.flex-shrink-0 {
  flex-shrink: 0;
}

.h5 {
  font-size: 1.25rem;
  margin-bottom: 0.5rem;
  font-weight: 500;
  line-height: 1.2;
}

/* 确保 Bootstrap Icons 正常显示 */
[class^="bi-"]::before,
[class*=" bi-"]::before {
  display: inline-block;
  font-family: bootstrap-icons !important;
  font-style: normal;
  font-weight: normal !important;
  font-variant: normal;
  text-transform: none;
  line-height: 1;
  vertical-align: -0.125em;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
</style>
